package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.zhentao.UserInfoThreadLocalUtil;
import com.zhentao.feign.product.ProductFeignClient;
import com.zhentao.model.entity.h5.CartInfo;
import com.zhentao.model.entity.product.ProductSku;
import com.zhentao.model.entity.user.UserInfo;
import com.zhentao.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate<String , String> redisTemplate;
    @Autowired
    private ProductFeignClient productFeignClient;
    private String getCartKey(Long userId) {
        //定义key user:cart:userId
        return "user:cart:" + userId;
    }
    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        // 获取当前登录用户的id
        UserInfo user = new UserInfo();
        user.setId(1l);
        String cartKey = getCartKey(user.getId());
        //获取缓存对象
        Object cartInfoObj = redisTemplate.opsForHash().get(cartKey, user.getId().toString());
        CartInfo cartInfo=null;
        if(cartInfoObj != null){
            //  如果购物车中有该商品，则商品数量 相加！
            cartInfo = JSON.parseObject(cartInfoObj.toString(), CartInfo.class);
            cartInfo.setSkuNum(cartInfo.getSkuNum()+skuNum);
            cartInfo.setIsChecked(1);
            cartInfo.setUpdateTime(new Date());
        }else {
            // 当购物车中没用该商品的时候，则直接添加到购物车！
            cartInfo=new CartInfo();
            // 购物车数据是从商品详情得到 {skuInfo}
            ProductSku productSku = productFeignClient.getBySkuId(skuId);
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuNum(skuNum);
            cartInfo.setSkuId(skuId);
            cartInfo.setUserId(user.getId());
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);
            cartInfo.setCreateTime(new Date());
            cartInfo.setUpdateTime(new Date());
        }
        // 将商品数据存储到购物车中
        redisTemplate.opsForHash().put(cartKey , String.valueOf(skuId) , JSON.toJSONString(cartInfo));

    }

    @Override
    public List<CartInfo> getCartList() {
        // 获取当前登录的用户信息
        UserInfo user = UserInfoThreadLocalUtil.getUser();
        String cartKey = getCartKey(user.getId());
        //获取数据
        List<Object> values = redisTemplate.opsForHash().values(cartKey);
        if(CollectionUtils.isNotEmpty(values)){
            List<CartInfo> cartInfoList = values.stream().map(cartInfoJSON ->
                            JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
                    .sorted(((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())))
                    .collect(Collectors.toList());
            return cartInfoList;
        }
        return new ArrayList<>() ;
    }

    @Override
    public void deleteCart(Long skuId) {
        // 获取当前登录的用户数据
        UserInfo user = UserInfoThreadLocalUtil.getUser();
        String cartKey = getCartKey(user.getId());
        //获取缓存对象
        redisTemplate.opsForHash().delete(cartKey,skuId.toString());
    }

    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        // 获取当前登录的用户数据
        UserInfo user = UserInfoThreadLocalUtil.getUser();
        String cartKey = getCartKey(user.getId());
        Boolean hasKey = redisTemplate.opsForHash().hasKey(cartKey, skuId.toString());
        if(hasKey){
            String cartInfoJSON = redisTemplate.opsForHash().get(cartKey, String.valueOf(skuId)).toString();
            CartInfo cartInfo = JSON.parseObject(cartInfoJSON, CartInfo.class);
            cartInfo.setIsChecked(isChecked);
            redisTemplate.opsForHash().put(cartKey,skuId.toString(),JSON.toJSONString(cartInfo));
        }
    }

    @Override
    public void allCheckCart(Integer isChecked) {
        // 获取当前登录的用户数据
        UserInfo user = UserInfoThreadLocalUtil.getUser();
        String cartKey = getCartKey(user.getId());
        // 获取所有的购物项数据
        List<Object> objectList = redisTemplate.opsForHash().values(cartKey);
        if(CollectionUtils.isNotEmpty(objectList)){
            objectList.stream().map(cartInfoJSON->{
                CartInfo cartInfo = JSON.parseObject(cartInfoJSON.toString(), CartInfo.class);
                cartInfo.setIsChecked(isChecked);
                return cartInfo;
            }).forEach(cartInfo -> redisTemplate.opsForHash().put(cartKey,cartInfo.getSkuId().toString(),
                    JSON.toJSONString(cartInfo)));
        }
    }

    @Override
    public void clearCart() {
        UserInfo user = UserInfoThreadLocalUtil.getUser();
        String cartKey = getCartKey(user.getId());
        redisTemplate.delete(cartKey);
    }

    @Override
    public List<CartInfo> getAllCkecked() {
        UserInfo user = UserInfoThreadLocalUtil.getUser();
        String cartKey = getCartKey(user.getId());
        // 获取所有的购物项数据
        List<Object> values = redisTemplate.opsForHash().values(cartKey);
        if(CollectionUtils.isNotEmpty(values)){
            List<CartInfo> collect = values.stream().map(cartInfoJSON ->
                            JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
                    .filter(cartInfo -> cartInfo.getIsChecked() == 1)
                    .collect(Collectors.toList());
            return collect;
        }
        return new ArrayList<>();
    }
}
